<?php

namespace mpend\modules\team\models;

use Yii;
use common\helpers\ArrayHelper;
use common\models\workbook\WorkbookRecord;
use common\logics\WorkbookLogic;
use common\models\workbook\WorkbookMember;

/**
 * 班组记工本管理模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class WorkBookStatsMemberSearch extends WorkbookMember {

    public static $begindate;
    public static $enddate;

    public function getDateCondition() {
        $begin = self::$begindate ?: date('Y-m-01');
        $end = self::$enddate ?: date('Y-m-d');
        return [
            'between', 'date', $begin, $end
        ];
    }

    /**
     * @inheritdoc
     */
    public function buildQuery($alias = 't') {
        $query = static::find();
        if ($alias) {
            $query->alias($alias);
            $alias .= '.';
        }
        $query->active(static::STATUS_ACTIVE);
        $query->joinWith([
            'workbook' => function($q) {
                return $q->alias('workbook')->active(WorkbookLogic::STATUS_ACTIVE);
            }
        ]);
        $query->andWhere([
            $alias . 'workbook_id' => $this->workbook_id,
            'workbook.type' => WorkbookLogic::TYPE_TEAM,
        ]);

        $query->orderBy([
            $alias . 'role_id' => SORT_DESC,
            $alias . 'created_at' => SORT_ASC,
        ]);
        $query->debug();
        return $query;
    }

    private $_stats = null;

    public function setStats() {
        $query = $this->getBooks($this->getDateCondition());
        $query->groupBy(['type']);
        $query->select([
            'type',
            'balance',
            'sum(amount) amount',
            'sum(workload) workload',
            'count(*) nums',
        ]);
        $query->debug();
        $data = $query->all();
        $this->_stats = ArrayHelper::index($data, 'type');
    }

    public function getWorkStats() {
        if ($this->_stats === null) {
            $this->setStats();
        }
        return $this->_stats;
    }

    public function getWorkloads() {
        $stats = $this->getWorkStats();
        return ArrayHelper::getValue($stats, [WorkbookRecord::TYPE_WORK, 'workload'], 0);
    }

    public function getWorkAmount() {
        $stats = $this->getWorkStats();
        return ArrayHelper::getValue($stats, [WorkbookRecord::TYPE_WORK, 'amount'], 0);
    }

    public function getLoan() {
        $stats = $this->getWorkStats();
        return ArrayHelper::getValue($stats, [WorkbookRecord::TYPE_LOAN, 'amount'], 0);
    }

    public function getBalance() {
        $stats = $this->getWorkStats();
        return ArrayHelper::getValue($stats, [WorkbookRecord::TYPE_BALANCE, 'amount'], 0);
    }

    public function getLoanAmount() {
        $stats = $this->getWorkStats();
        $amount = 0;
        foreach ($stats as $item) {
            if ($item->type == WorkbookRecord::TYPE_BALANCE) {
                continue;
            }
            $amount += $item->balance * $item->amount;
        }
        return $amount;
    }

    public function getBalanceAmount() {
        $stats = $this->getWorkStats();
        $amount = 0;
        foreach ($stats as $item) {
            $amount += $item->balance * $item->amount;
        }
        return $amount;
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'realname' => '姓名',
            'workloads' => '总共数(工)',
            'workAmount' => '总共钱(元)',
            'loan' => '借支(元)',
            'balance' => '已结工钱(元)',
            'loanAmount' => "统计一\r(总工钱-借支)",
            'balanceAmount' => "统计二\r（总工钱-借支-已给工钱）",
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function fields() {
        return [
            'id',
            'realname',
            'workloads',
            'amount',
            'loan',
            'balance',
            'loanAmount',
            'balanceAmount',
        ];
    }

}
